<template>
    <div class="tech-add-or-edit">
        <el-form ref="natureForm" v-model="form" label-position="left" inline class="demo-table-expand">
            <el-form-item prop="src" label="物品贴图">
                <ossUpload :imageUrl="form.src ? domain + form.src : ''" :imgName="randomName"
                    @upload-img="handlerUpload" />
            </el-form-item>
            <el-form-item prop="name" label="中文名称">
                <el-input v-model="form.name" placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-form-item prop="name" label="品质">
                <el-select v-model="form.quality" placeholder="请选择品质">
                    <el-option v-for="item in qualityOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="price" label="价格">
                <el-input-number v-model="form.price" :max="100" placeholder="请输入内容">
                </el-input-number>
            </el-form-item>
            <el-form-item prop="tag" label="标签">
                <el-select v-model="form.tag" multiple placeholder="请选择">
                    <el-option v-for="item in options" :key="item._id" :label="item.name" :value="item._id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="originalItem" label="原版物品">
                <CompositionItem :selectedArr.sync="form.originalItem" :showNum="false" :mid="$route.query.mid"
                    :module="['materials', 'natures', 'heros']" />
            </el-form-item>
            <el-form-item prop="extraLink" label="额外链接">
                <ExtraCompositionItem :selectedArr.sync="form.extraLink" :mid="$route.query.mid" :module="module" />
            </el-form-item>
            <el-form-item prop="extraLink" label="额外属性">
                <ExtraProperty :list.sync="form.extraProperty" />
            </el-form-item>
            <mavon-editor v-model="form.introduce" @imgAdd="imgUpload" class="editor-sty" :boxShadow="false" ref="md">
            </mavon-editor>
        </el-form>
        <el-button type="primary" @click="addItem" style="margin-top: 16px">
            {{
            $route.query.type === "edit" ? "更新" : "提交"
            }}
        </el-button>
    </div>
</template>

<script>
    import ossUpload from "@/components/ossUpload.vue";
    import CompositionItem from "@/components/CompositionItem.vue";
    import ExtraCompositionItem from "@/components/ExtraCompositionItem.vue";
    import ExtraProperty from "@/components/ExtraProperty.vue";
    import md5 from "md5-js";
    import OSS from "ali-oss";

    export default {
        name: "natureAddOrEdit",
        data() {
            return {
                module: ["materials", "foods", "anims", "natures", "heros"],
                options: [], // 标签选择项
                searchData: [],
                form: {
                    src: "",
                    name: "",
                    alis: "",
                    quality: '',
                    tag: [],
                    introduce: "",
                    originalItem: [],
                    extraProperty: [],
                    extraLink: [],
                },
                qualityOptions: [
                    {
                        label: '普通',
                        value: '1'
                    },
                    {
                        label: '经典',
                        value: '2'
                    },
                    {
                        label: '漂亮',
                        value: '3'
                    },
                    {
                        label: '杰出',
                        value: '4'
                    },
                    {
                        label: '优雅',
                        value: '5'
                    },
                    {
                        label: '忠诚',
                        value: '6'
                    },
                    {
                        label: '事件',
                        value: '7'
                    },
                ]
            };
        },
        components: {
            ossUpload,
            CompositionItem,
            ExtraCompositionItem,
            ExtraProperty
        },
        computed: {
            randomName: {
                get: function () {
                    let time = new Date();
                    return md5(time);
                },
                cache: false,
            },
        },
        async activated() {
            await this.getTag();
            if (this.$route.query.type === "edit") {
                this.fetchDetail();
            }
        },
        deactivated() {
            this.form = {
                src: "",
                name: "",
                alis: "",
                quality: '',
                tag: [],
                introduce: "",
                originalItem: [],
                extraProperty: [],
                extraLink: [],
            };
        },
        methods: {
            /**
             * 获取详情数据
             **/
            async fetchDetail() {
                let res = await this.axios.get("modskin/single", {
                    params: {
                        id: this.$route.query.id,
                    },
                });
                let temp = this.showDataTransform(res.data, [
                    { originalItem: false, key: "originalItem" },
                    { hasList: true, key: "extraLink" },
                ]);
                temp.tag = temp.tag.map((val) => {
                    return val._id;
                });
                this.form = temp;
            },
            /**
             * @description 获取科技对应的标签
             */
            async getTag() {
                let res = await this.$store.dispatch("getTags", {
                    kind: "skins",
                    mid: this.$route.query.mid,
                });
                this.options = res;
            },
            /**
             * @description 科技新增或修改
             */
            async addItem() {
                let requestUrl =
                    this.$route.query.type === "edit"
                        ? "/modskin/update"
                        : "/modskin/add";
                let [_originalItem] = this.transformSumbitData([
                    {
                        list: this.form.originalItem,
                        needNum: false,
                    },
                ]);
                let _extraLink = this.transformSumbitDataList(this.form.extraLink)
                let res = await this.axios.post(requestUrl, {
                    ...this.form,
                    id: this.form._id,
                    extraLink: _extraLink,
                    originalItem: _originalItem,
                });
                if (!res.data.code) {
                    this.$message.success("添加成功");
                    this.$router.go(-1);
                }
            },
            handlerUpload(src) {
                this.form.src = src;
            },
            /**
             * 图片上传
             */
            imgUpload(filename, $file) {
                // oss配置
                const client = new OSS({
                    endpoint: "oss-cn-beijing.aliyuncs.com",
                    accessKeyId: "LTAI4FgrsFXo8ij335BxeRbp",
                    accessKeySecret: "oG0PWkV0qOeDoJQfwEHOqIvTp16S0x",
                    bucket: "stavebox",
                });
                // 图片路径拼接，dirName其实就是定义存在oss的哪个虚拟文件夹下的
                let time = new Date();
                let hash = md5(time);
                let imgType = $file.type.split("/")[1];
                let hashName = "Article/" + hash + "." + imgType;
                // 将文件流上传至oss
                client
                    .put(hashName, $file)
                    .then((res) => {
                        let imgUrl = this.domain + res.name;
                        this.$refs.md.$img2Url(filename, imgUrl);
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            },
        },
    };
</script>

<style lang="scss">
    .tech-add-or-edit {
        .demo-table-expand {
            font-size: 0;
        }

        .demo-table-expand label {
            width: 120px;
            color: #99a9bf;
        }

        .demo-table-expand .el-form-item {
            margin-right: 0;
            margin-bottom: 16px;
            width: 50%;
        }
    }
</style>
<style lang="scss" scoped>
    .tech-add-or-edit {
        padding: 16px;

        .delete-button,
        .add-button {
            display: inline-block;
            width: 60px;
            flex-shrink: 0;
        }

        .material {
            margin-bottom: 10px;
        }

        .attr-container {
            display: flex;
            height: 50px;
        }
    }
</style>